package com.aizhixin.lab.course.course.service;

import com.aizhixin.lab.course.course.entity.Course;
import com.aizhixin.lab.course.course.entity.CourseChapterLike;
import com.aizhixin.lab.course.course.entity.CourseLike;
import com.aizhixin.lab.course.course.entity.TeacherLike;
import com.aizhixin.lab.course.course.repository.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Slf4j
@Service
@Transactional
public class StuLikeService {
    @Autowired
    private TeacherLikeRepository teacherLikeRepository;
    @Autowired
    private CourseLikeRepository courseLikeRepository;
    @Autowired
    private CourseChapterLikeRepository chapterLikeRepository;
    @Autowired
    private CourseRepository courseRepository;
    public void teacherLike(String courseId,Long teacherId,Long createdId){
        TeacherLike teacherLike = teacherLikeRepository.findByCreatedByAndTeacherIdAndCourseId(createdId, teacherId, courseId);
        if (Objects.isNull(teacherLike)){
            teacherLike = new TeacherLike();
            teacherLike.setCourseId(courseId);
            teacherLike.setCreatedBy(createdId);
            teacherLike.setTeacherId(teacherId);
            teacherLikeRepository.save(teacherLike);
        }else {
            teacherLikeRepository.delete(teacherLike.getId());
        }
    }
    public void courseLike(String courseId,Long createId){
        CourseLike courseLike = courseLikeRepository.findByCourseIdAndCreatedBy(courseId, createId);
        if (Objects.isNull(courseLike)){
           courseLike=new CourseLike();
           courseLike.setCourseId(courseId);
           courseLike.setCreatedBy(createId);
            Course course = courseRepository.findCourseById(courseId);
            if (!Objects.isNull(course)){
                courseLike.setTemplateId(course.getTemplateId());
                courseLikeRepository.save(courseLike);
            }
        }else {
            courseLikeRepository.delete(courseLike.getId());
        }
    }
    public void chapterLike(Long chapterId,Long createdId){
        CourseChapterLike courseChapterLike = chapterLikeRepository.findByChapterIdAndCreatedBy(chapterId, createdId);
        if (Objects.isNull(courseChapterLike)){
            courseChapterLike=new CourseChapterLike();
            courseChapterLike.setChapterId(chapterId);
            courseChapterLike.setCreatedBy(createdId);
            chapterLikeRepository.save(courseChapterLike);
        }else {
            chapterLikeRepository.delete(courseChapterLike.getId());
        }

    }
}
